import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/pages/goods/entity/activity_item_entity.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';

//特价商品控制器
class DiscountGoodsController extends BaseController {
  //当前页码
  int page = 1;

  //是否有下一页
  bool hasNextPage = true;

  final ScrollController scrollController = ScrollController();

  List<ActivityItemEntity> itemList = [];

  int selected = 0;

  int nowDoing = 0;

  //商品列表
  List goodsList = [];

  @override
  void onInit() {
    getActivityTimes();
    super.onInit();
    UmengCommonSdk.onPageStart('特价商品');
  }

  //获取时间列表
  Future getActivityTimes() async {
    Tools.showLoading();
    Network.getActivityTimes("5", activityType: '1').then((value) {
      itemList = value
          .map((item) {
            try {
              return ActivityItemEntity.fromJson(item);
            } catch (e) {
              return null; // 转换失败时返回 null
            }
          })
          .where((item) => item != null)
          .cast<ActivityItemEntity>()
          .toList();
      if (itemList.isNotEmpty) {
        for (int index = 0; index < itemList.length; index++) {
          itemList[index].type = 0;
        }
        if (itemList.length > 1) {
          itemList[1].type = 1;
        }
        onPageRefresh();
      }
      update();
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  //获取特价商品列表
  Future specialGoodsList() async {
    Tools.showLoading();
    Network.getSpecialGoodsList({"marketingId": itemList[selected].marketingId, "sid": AppData.sid, "pageNum": page, "pageSize": 10}).then((value) {
      hasNextPage = value['hasNextPage'];
      if (page > 1) {
        goodsList.addAll(value['list']);
      } else {
        goodsList = value['list'];
      }
      update();
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  //选择活动
  void change(int index) {
    selected = index;

    page = 1;

    itemList.forEach((element) {
      element.type = 0;
    });

    if (index == 0) {
      itemList[index + 1].type = 1;
    }

    if (index > 0 && index < (itemList.length)) {
      itemList[index - 1].type = 2;
      if (index < itemList.length - 1) {
        itemList[index + 1].type = 1;
      }
    }
    scrollToTopSmooth();
    specialGoodsList();
    update();
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    page = 1;
    await specialGoodsList();
    // 完成下拉刷新，并重置 footer 状态
    baseRefreshCtr.refreshCompleted(resetFooterState: !hasNextPage);
    // 根据是否有更多数据来设置 footer 的状态
    if (hasNextPage) {
      baseRefreshCtr.resetNoData(); // 重置为上拉加载状态
    } else {
      baseRefreshCtr.loadNoData(); // 显示 "没有更多数据"
    }
  }

  @override
  void onPageLoading() async {
    super.onPageLoading();
    if (hasNextPage) {
      page += 1;
      await specialGoodsList();
      baseRefreshCtr.loadComplete();
    } else {
      baseRefreshCtr.loadNoData();
    }
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.dispose();
    UmengCommonSdk.onPageEnd('特价商品');
  }

  // 平滑滚动到顶部
  void scrollToTopSmooth() {
    scrollController.animateTo(
      0.0, // 滚动到顶部的位置
      duration: const Duration(milliseconds: 300), // 动画持续时间
      curve: Curves.easeInOut, // 滚动曲线
    );
  }
}
